from sanic.views import HTTPMethodView
from sanic.response import text,json
import urllib3
import json as jn
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
from processing.comm import sqlPaging,sqlOrder,set_status,timestamp_to_standard,order_log
from processing.Sql_DataFrom import ProJosn

class xiaOrder(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        html_data = request.json
        client_ip = request.ip
        user_id = request.app.ctx.user_id
        openid = ''
        phone = ''
        businessId = ''
        goodsSku = html_data['goodsSku']

        try:
            # 查询用户
            # 先查询用户
            user_sql = f"""
                    select users.nickName,users.openid,users.head_img,users.phone,re.residue from rechargerecord as re 
                    JOIN c_users as users on re.openid=users.openid  where re.merchant_id='{user_id}' and re.residue > 0  and users.openid='{html_data['wechat_openid']}'
                """
            userData = db.find_all(user_sql)
            titleList = ['nickName', 'openid', 'head_img', 'phone', 'money']

            userData = ProJosn(userData, titleList, 'list', groupType='orderSum')

            # 下单前先排查商品是否是快递  快递得排查地址
            goods_sql = f"""
                        select businessId,goodsType,goodsSkuJson from goods where merchant_id='{user_id}' and goods_id='{html_data['goods_id']}'
                    """
            address_id = ''
            goods_data = db.find_one(goods_sql)
            if goods_data:
                businessId = goods_data[0]
                # 判断商品是否是快递
                if goods_data[1] == 1 or goods_data[1] == 5:
                    # return json({'code': 201, 'message': "请填写您得收货地址再购买!"})
                    address_sql = f"""
                        select id from user_address where merchant_id='{user_id}' and openid='{html_data['wechat_openid']}' and user_use=1
                    """
                    address_data = db.find_one(address_sql)

                    if address_data:
                        address_id = address_data[0]
                    else:
                        return json({'code': 201, 'message': "请填写您得收货地址再购买!"})
                else:
                    pass
            else:
                return json({'code': 201, 'message': "未找到该商品!"})

            if db.find_one(goods_sql):


                # # 查询商品归属店铺
                # if html_data['businessId']:
                #     if (db.find_one(goods_sql)[0]) == html_data['businessId']:
                #         businessId = html_data['businessId']

                # else:
                    # 未设置店铺
                    # pass

                #     1.微信支付
                if html_data['paypal_type'] == 1:
                    return json({'code': 201, 'message': "未开通微信支付！"})
                #     2.支付宝支付
                elif html_data['paypal_type'] == 2:
                    return json({'code': 201, 'message': "未开通支付宝支付！"})
                #     3.余额支付
                elif html_data['paypal_type'] == 3:
                    #     查询余额
                    rechargerecord_sql = f"select residue,id from rechargerecord where openid='{html_data['wechat_openid']}' and paymentStatus='1' and residue>0"
                    balance = [i for i in db.find_all(rechargerecord_sql)]
                    """
                        支付逻辑
                            1.先提取商品规格价格*数量
                    """
                    # 获取商品规格

                    balance_total1 = 0
                    balance_total = [i[0] + balance_total1 for i in db.find_all(rechargerecord_sql)]

                    # 单规格
                    if goodsSku == 1:
                        goods_sql = f"select goodsPrice,stockNum from goods where goods_id='{html_data['goods_id']}'"
                        goods_price_one = db.find_one(goods_sql)
                        goods_stockNum = goods_price_one[1]
                        goods_price_one = db.find_one(goods_sql)[0]


                        if goods_stockNum-int(html_data['quantity'])<0:
                            return json({'code': 202, 'message': "库存不够！"})

                        goods_price = goods_price_one * html_data['quantity']

                        if sum(balance_total) < goods_price:
                            return json({'code': 202, 'message': "余额不足！"})
                        for b in balance:
                            b_result = b[0] - goods_price
                            if b_result <= 0:
                                # 扣除余额
                                balance_sql_update = f"update rechargerecord set residue=0,paymentStatus='4' where id={b[1]}"
                                db.update(balance_sql_update)
                                continue
                            else:
                                # 如果第一份充值余额不够扣除第二份
                                balance_sql_update = f"update rechargerecord set residue={b_result}  where id={b[1]}"
                                db.update(balance_sql_update)
                                break
                            # 生成订单
                        order_id = Random_id(32, 'ORDER')

                        order_create_sql = f"""insert into goods_order(address_id,merchant_id,order_id,business_id,wechat_openid
                                               ,wechatphone,wechatNickname,wechatavatar,goods_id,goods_sku,order_type,paypal_type,total_money,goods_money,goodsQuantity,payStatus,status,ctime,utime
                                               ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),now())"""

                        db.insert(order_create_sql, (
                            address_id,
                            user_id,
                            order_id,
                            businessId,
                            html_data['wechat_openid'],
                            userData[0]['phone'],
                            userData[0]['nickName'],
                            userData[0]['head_img'],
                            html_data['goods_id'],
                            '',
                            html_data['order_type'],
                            html_data['paypal_type'],
                            float(goods_price),
                            float(goods_price_one),
                            int(html_data['quantity']),
                            3,
                            '支付成功'
                        ))

                        # 减少库存
                        goodsjs_sql = f"""
                            update goods set stockNum=%s where goods_id=%s
                        """

                        db.update(goodsjs_sql,(
                            (goods_stockNum-int(html_data['quantity'])),
                            html_data['goods_id']
                        ))

                        return json({'code': 200, 'message': "支付成功！"})
                    # 多规格
                    elif goodsSku == 2:

                        # 查看库存
                        goodsSkuJson = eval(goods_data[2])
                        for i in goodsSkuJson['list1']:
                            if i['id'] == html_data['uuid']:
                                if int(i['stock'])>=html_data['quantity']:
                                    goods_price = float(i['price']) * int(html_data['quantity'])

                                    if sum(balance_total) < goods_price:
                                        return json({'code': 202, 'message': "余额不足！"})
                                    for b in balance:
                                        b_result = b[0] - goods_price
                                        if b_result <= 0:
                                            # 扣除余额
                                            balance_sql_update = f"update rechargerecord set residue=0,paymentStatus='4' where id={b[1]}"
                                            db.update(balance_sql_update)
                                            continue
                                        else:
                                            # 如果第一份充值余额不够扣除第二份
                                            balance_sql_update = f"update rechargerecord set residue={b_result}  where id={b[1]}"
                                            db.update(balance_sql_update)
                                            break
                                        # 生成订单

                                    order_id = Random_id(32, 'ORDER')
                                    order_create_sql = f"""insert into goods_order(address_id,merchant_id,order_id,business_id,wechat_openid
                                           ,wechatphone,wechatNickname,wechatavatar,goods_id,goods_sku,order_type,paypal_type,total_money,goods_money,payStatus,goodsQuantity,status,ctime,utime
                                           ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),now())"""

                                    # print(html_data['quantity'])
                                    db.insert(order_create_sql, (
                                        address_id,
                                        user_id,
                                        order_id,
                                        businessId,
                                        html_data['wechat_openid'],
                                        userData[0]['phone'],
                                        userData[0]['nickName'],
                                        userData[0]['head_img'],
                                        html_data['goods_id'],
                                        jn.dumps(i),
                                        html_data['order_type'],
                                        html_data['paypal_type'],
                                        float(goods_price),
                                        float(html_data['money']),
                                        3,
                                        int(html_data['quantity']),
                                        '支付成功'
                                    ))

                                    i['stock'] = int(i['stock']) - int(html_data['quantity'])
                                    # 减少库存
                                    goodsjs_sql = f"""
                                       update goods set goodsSkuJson=%s where goods_id=%s
                                   """
                                    db.update(goodsjs_sql,(jn.dumps(goodsSkuJson),html_data['goods_id']))
                                    return json({'code': 200, 'message': "支付成功！"})
                                else:
                                    return json({'code': 202, 'message': "库存不够！"})

                            else:
                                pass


                #     4.月卡支付
                elif html_data['paypal_type'] == '4':
                    return json({'code': 201, 'message': "未开通月卡支付！"})
            else:
                return json({'code': 201, 'message': "商品不存在！"})

            return json({'code': 200, 'message': "请求成功！"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/order/createOrder', error))
            if openid:
                return json({'code': 500, 'message': "后端代码出错！"})
            else:
                return json({'code': 500, 'message': "appid或serct不对或openid错误！"})
# class wechatPlaceAnOrder(HTTPMethodView):
#     async def post(self, request):
#         db = request.app.ctx.db
#         # 获取用户列表
#         user_id = request.app.ctx.user_id
#         client_ip = request.ip
#
#         html_data = request.json
#
#         try:
#             # 先查询用户
#             user_sql = f"""
#                 select users.nickName,users.openid,users.head_img,users.phone,re.residue from rechargerecord as re
#                 JOIN c_users as users on re.openid=users.openid  where re.merchant_id='{user_id}' and re.residue > 0  and users.openid='{html_data['openid']}'
#             """
#             userData = db.find_all(user_sql)
#             titleList = ['nickName', 'openid', 'head_img', 'phone', 'money']
#
#             userData = ProJosn(userData,titleList,'list',groupType='orderSum')
#
#
#             # 下单前先排查商品是否是快递  快递得排查地址
#             goods_sql = f"""
#                 select goodsType from goods where merchant_id='{user_id}' and goods_id='{html_data['goods_id']}'
#             """
#             address_id = ''
#             goods_data = db.find_one(goods_sql)
#             if goods_data:
#                 # 判断商品是否是快递
#                 if goods_data[0] == 1 or goods_data[0] == 5:
#                     return json({'code': 201, 'message': "请填写您得收货地址再购买!"})
#                     # address_sql = f"""
#                     #     select id from user_address where merchant_id='{user_id}' and openid='{html_data['openid']}' and user_use=1
#                     # """
#                     # address_data = db.find_one(address_sql)
#                     # if address_data:
#                     #     address_id = address_data[0]
#                     # else:
#                     #     return json({'code': 201, 'message': "请填写您得收货地址再购买!"})
#                 else:
#                     pass
#             else:
#                 return json({'code': 201, 'message': "未找到该商品!"})
#
#
#             goodsPrice = float(html_data['goodsPrice']) # 商品价格
#             if len(userData):
#                 userData = userData[0]
#
#                 # 判断商品价格是否大于余额
#                 if userData['money'] >= goodsPrice:
#                     rechargerecord_sql = f"""
#                         select residue,id from rechargerecord where openid='{userData['openid']}' and residue>0
#                     """
#
#                     money_sql = f"""
#                         select sum(residue) as money from rechargerecord where openid='{userData['openid']}' and residue>0
#                     """
#                     money = db.find_one(money_sql)[0]
#
#                     rechargerecord = db.find_all(rechargerecord_sql)
#                     rechargerecord = ProJosn(rechargerecord,rechargerecord_sql)
#
#                     if money >= goodsPrice:
#
#                         for i in rechargerecord:
#
#                             if goodsPrice <= (i['residue']):
#
#                                 recharge_sql = f"""
#                                     update rechargerecord set residue=%s,paymentStatus=%s where id='{i['id']}'
#                                 """
#                                 if i['residue'] - goodsPrice > 0:
#                                     paymentStatus = '1'
#                                     goodsPrice =  i['residue'] - goodsPrice
#                                 else:
#                                     paymentStatus = '4'
#                                     goodsPrice = goodsPrice - i['residue']
#                                 db.update(recharge_sql,(
#                                     goodsPrice,
#                                     paymentStatus
#                                 ))
#
#                                 # 生成订单
#                                 order_id = Random_id(32, 'ORDER')
#                                 order_sql = f"""
#                                     insert into goods_order(merchant_id,order_id,address_id,business_id,wechat_openid,wechatNickname,wechatavatar,wechatphone,goods_id,order_type,paypal_type,total_money,
#                                         goods_money,payStatus,utime,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),now())
#                                 """
#                                 db.insert(order_sql,(
#                                     user_id,
#                                     order_id,
#                                     address_id,
#                                     html_data['businessId'],
#                                     html_data['openid'],
#                                     html_data['nickName'],
#                                     html_data['head_img'],
#                                     html_data['phone'],
#                                     html_data['goods_id'],
#                                     html_data['order_type'],
#                                     html_data['paypal_type'],
#                                     float(html_data['goodsPrice']),
#                                     float(html_data['goodsPrice']),
#                                     '3'
#                                 ))
#
#                                 return json({'code': 200, 'message': "请求成功!"})
#                             elif goodsPrice > i['residue']:
#                                 goodsPrice = goodsPrice - i['residue']
#                                 if goodsPrice > 0:
#                                     recharge_sql = f"""
#                                         update rechargerecord set residue=%s,paymentStatus=%s where id='{i['id']}'
#                                     """

#                                     db.update(recharge_sql, (
#                                         0,
#                                         '4'
#                                     ))
#                                 else:
#                                     return json({'code': 201, 'message': "余额不足!"})
#                             else:
#                                 return json({'code': 201, 'message': "余额不足!"})
#                     else:
#                         return json({'code': 201, 'message': "余额不足!"})
#                 else:
#                     return json({'code': 201, 'message': "余额不足!"})
#             else:
#                 return json({'code': 201, 'message': "用户不存在!"})
#
#
#             # return json({'code': 200, 'message': "下单成功!"})
#
#         except Exception as error:
#             error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
#             db.insert(error_sql, (client_ip, '/commodity/order/placeAnOrder', error))
#             data = {
#                 'code':500,
#                 'message':'后端报错!'
#             }
#             return json(data)




class getOrderDetails(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip

        order_id = (request.args.get('order_id', ''))

        try:


            sql = f"""
                select order_id,business_id,wechatNickname,wechatavatar,wechatphone,goods_id,goods_sku,order_type,paypal_type,distribution_type,total_money,goods_money,status,paypalDetails,payStatus,address_id,goodsQuantity,user_info,goods_info,business_info,ctime from goods_order where merchant_id='{user_id}' and wechat_openid='{openid}' and order_id='{order_id}'
            """

            data = db.find_all(sql)
            if data:
                data = ProJosn(data,sql)[0]
            else:
                data = ''

            return json({
                'code': 200,
                'data': {
                    'orderDetails':data
                },
                'message': "请求成功!"
            })

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class order_confirm(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip
        html_data = request.json

        try:
            sql = f"""
                insert into goods_order(address_id,merchant_id,order_id,business_id,goods_id,order_type,paypal_type,goods_info,user_info,business_info,goods_sku,payStatus,wechat_openid,goodsQuantity,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
            """
            order_id = Random_id(32, 'ORDER')

            db.insert(sql,(
                0,
                user_id,
                order_id,
                html_data['business_id'],
                html_data['goods_id'],
                html_data['order_type'],
                html_data['paypal_type'],
                html_data['goods_info'],
                html_data['user_info'],
                html_data['business_info'],
                html_data['goods_sku'],
                '1',
                html_data['openid'],
                html_data['quantity']
            ))

            # 查询订单是否生成
            order_info_find = f"""
                select * from goods_order where order_id='{order_id}'
            """
            if db.find_one(order_info_find):
                # 生成日志
                code = order_log(db,{
                    'merchant_id':user_id,
                    'order_id':order_id,
                    'order_log':'生成订单,未支付',
                    'content':'',
                    'goods_info':html_data['goods_info'],
                    'user_info':html_data['user_info'],
                    'type':html_data['type'],
                    'payStatus':html_data['payStatus'],
                    'openid':html_data['openid'],
                    'order_info':str(jn.dumps({
                        'user_id':user_id,
                        'order_id':order_id,
                        'business_id':html_data['business_id'],
                        'goods_id':html_data['goods_id'],
                        'order_type':html_data['order_type'],
                        'paypal_type':html_data['paypal_type'],
                        'goods_info':html_data['goods_info'],
                        'user_info':html_data['user_info'],
                        'business_info':html_data['business_info'],
                        'goods_sku':html_data['goods_sku'],
                        'payStatus':html_data['payStatus'],
                        'openid':html_data['openid'],
                        'quantity':html_data['quantity']
                    }))
                })
                if code == 200:
                    return json({
                        'code': 200,
                        'data':{
                          'order_id':order_id
                        },
                        'message': "请求成功!"
                    })
                else:
                    return json({
                        'code': 500,
                        'message': "订单生成失败!"
                    })

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class order_confirm_status0(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip
        html_data = request.json
        paypalDetails = '' # 微信支付拉去支付的参数
        coupon_price = 0  # 局部优惠券价格
        my_coupon_id = 0 # 由于有一个可能存在多个优惠券  所以指定自己领取的优惠券id
        order_message = ''  # 日志
        distributionFee = 0  # 固定邮费
        goods_info = jn.loads(html_data['goods_info']) # 商品信息
        try:

            # 判断支付逻辑
            _payment = ''
            #     1.微信支付
            if html_data['paypal_type'] == 1:
                # 处理完的数据放入 paypalDetails
                return json({'code': 201, 'message': "未开通微信支付！"})
            #     2.支付宝支付
            elif html_data['paypal_type'] == 2:
                return json({'code': 201, 'message': "未开通支付宝支付！"})
            #     3.余额支付
            elif html_data['paypal_type'] == 3:
                # 余额支付没有paypalDetails

                #     查询余额
                rechargerecord_sql = f"select residue,id from rechargerecord where openid='{openid}' and paymentStatus='1' and residue>0"
                balance = [i for i in db.find_all(rechargerecord_sql)]
                """
                    支付逻辑
                        1.先提取商品规格价格*数量eval
                """
                # 获取商品规格

                balance_total1 = 0
                balance_total = [i[0] + balance_total1 for i in db.find_all(rechargerecord_sql)]

                # 判断是否使用优惠券
                if html_data['coupon_id']:
                    coupon_sql = f"""
                        select coupons.moneys,my_coupons.id from my_coupons join coupons on my_coupons.coupons_id=coupons.id where my_coupons.merchant_id='{user_id}' and my_coupons.openid='{openid}' and my_coupons.coupons_id={html_data['coupon_id']} and my_coupons.status='0'
                    """
                    coupon_data = db.find_one(coupon_sql)
                    if coupon_data:
                        coupon_price = coupon_data[0]
                        my_coupon_id = coupon_data[1]
                        order_message +=f'使用优惠券减{coupon_price}价格;'

                # 判断是否有配送费

                if goods_info['distributionType'] == '固定邮费':
                    distributionFee = eval(goods_info['distributionFee'])


                # 单规格
                if html_data['goodsSkuType'] == '单规格':
                    goods_sql = f"select goodsPrice,stockNum from goods where goods_id='{html_data['goods_id']}'"
                    goods_price_one_data = db.find_one(goods_sql)
                    goods_stockNum = int(goods_price_one_data[1])
                    goods_price_one = float(goods_price_one_data[0])

                    if goods_stockNum - int(html_data['goodsQuantity']) < 0:
                        return json({'code': 202, 'message': "库存不够！"})

                    goods_price = goods_price_one * html_data['goodsQuantity'] - coupon_price # 在商品价格的基础上减去优惠的价格
                    goods_price += distributionFee # 邮费

                    html_data['total_money'] = goods_price
                    if sum(balance_total) < goods_price:  # balance_total 用户余额
                        return json({'code': 202, 'message': "余额不足！"})
                    for b in balance:
                        b_result = b[0] - goods_price
                        if b_result <= 0:
                            # 扣除余额
                            balance_sql_update = f"update rechargerecord set residue=0,paymentStatus='4' where id={b[1]}"
                            db.update(balance_sql_update)
                            continue
                        else:
                            # 如果第一份充值余额不够扣除第二份
                            balance_sql_update = f"update rechargerecord set residue={b_result}  where id={b[1]}"
                            db.update(balance_sql_update)
                            break

                    # 减少库存
                    goodsjs_sql = f"""
                        update goods set stockNum=%s where goods_id=%s
                    """

                    db.update(goodsjs_sql, (
                        (goods_stockNum - int(html_data['goodsQuantity'])),
                        html_data['goods_id']
                    ))
                    _payment = f'支付成功({goods_price}价格)'
                    order_message += f'支付成功({goods_price}价格);'
                    if html_data['paypal_type'] == 3:
                        html_data['payStatus'] = 3
                    # return json({'code': 200, 'message': "支付成功！"})
                # 多规格
                elif html_data['goodsSkuType'] == '多规格':
                    # 查看库存

                    goodsSkuJson = (html_data['goodsSkuJson'])
                    for i in goodsSkuJson['list1']:

                        if i['skuId'] == html_data['goods_sku']['skuId']:
                            if int(i['skuStockNum']) >= html_data['goodsQuantity']:
                                goods_price = float(i['skuPrice']) * int(html_data['goodsQuantity']) - coupon_price
                                goods_price += distributionFee  # 邮费
                                html_data['total_money'] = goods_price
                                if sum(balance_total) < goods_price:  #写优惠券逻辑
                                    return json({'code': 202, 'message': "余额不足！"})
                                for b in balance:
                                    b_result = b[0] - goods_price
                                    if b_result <= 0:
                                        # 扣除余额
                                        balance_sql_update = f"update rechargerecord set residue=0,paymentStatus='4' where id={b[1]}"
                                        db.update(balance_sql_update)
                                        continue
                                    else:
                                        # 如果第一份充值余额不够扣除第二份
                                        balance_sql_update = f"update rechargerecord set residue={b_result}  where id={b[1]}"
                                        db.update(balance_sql_update)
                                        break
                                    # 生成订单

                                i['skuStockNum'] = int(i['skuStockNum']) - int(html_data['goodsQuantity'])
                                # 减少库存
                                goodsjs_sql = f"""
                                       update goods set goodsSkuJson=%s where goods_id=%s
                                   """
                                db.update(goodsjs_sql, (jn.dumps(goodsSkuJson), html_data['goods_id']))

                                _payment = '支付成功'
                                order_message += f'支付成功({goods_price}价格);'
                                html_data['payStatus'] = 3
                            else:
                                return json({'code': 202, 'message': "库存不够！"})

                        else:
                            pass

            #     4.月卡支付
            elif html_data['paypal_type'] == '4':
                return json({'code': 201, 'message': "未开通月卡支付！"})



            sql = f"""
                update goods_order set paypal_type={html_data['paypal_type']},distribution_type='{html_data['distribution_type']}',total_money={float(html_data['total_money'])},
                paypalDetails='{paypalDetails}',payStatus={html_data['payStatus']},address_id={html_data['address_id']},goodsQuantity={html_data['goodsQuantity']},memo='{html_data['memo']}',
                coupon_id='{html_data['coupon_id']}',utime=now(),ctime=now()
                where merchant_id='{user_id}' and order_id='{html_data["order_id"]}'
            """
            #                 html_data['paypal_type'],  #支付类型 1微信支付、2支付宝支付、3余额支付、4月卡支付丶5积分支付
            #                 html_data['distribution_type'],  # 配送方式
            #                 float(html_data['total_money']),  # 实际支付金额 或积分 或 余额
            #                 paypalDetails, # 支付参数  这里需要调用微信支付解密之后拉取支付传的
            #                 html_data['payStatus'], #1.确认订单,2.支付中,3.已支付,4.待发货,5.已发货,6.待收货,7.已收货,8.已退款,0.待支付

            db.update(sql)

            # 减少使用的优惠券
            if coupon_price>0:
                coupon_sql = f"""
                      update my_coupons set status='1' where id={my_coupon_id}
                  """
                db.update(coupon_sql)

            # 查询订单是否生成
            order_info_find = f"""
                select * from goods_order where order_id='{html_data['order_id']}'
            """
            if db.find_one(order_info_find):
                # 生成日志
                logs = '生成错误订单'
                if html_data['payStatus'] == 0:
                    order_message += '生成订单,待支付;'
                if html_data['payStatus'] == 3:
                    logs += '生成订单,已支付;'

                code = order_log(db,{
                    'merchant_id':user_id,
                    'order_id':html_data['order_id'],
                    'order_log':order_message,
                    'content':'',
                    'goods_info':html_data['goods_info'],
                    'user_info':html_data['user_info'],
                    'type':html_data['type'],
                    'payStatus':html_data['payStatus'],
                    'openid':html_data['openid'],
                    'order_info':str(jn.dumps({
                        'user_id':user_id,
                        'order_id':html_data['order_id'],
                        'business_id':html_data['business_id'],
                        'goods_id':html_data['goods_id'],
                        'order_type':html_data['order_type'],
                        'paypal_type':html_data['paypal_type'],
                        'goods_info':html_data['goods_info'],
                        'user_info':html_data['user_info'],
                        'business_info':html_data['business_info'],
                        'goods_sku':html_data['goods_sku'],
                        'payStatus':html_data['payStatus'],
                        'openid':html_data['openid'],
                        'goodsQuantity':html_data['goodsQuantity']
                    }))
                })
                if code == 200:
                    return json({
                        'code': 200,
                        'message': '支付成功'
                    })
                else:
                    return json({
                        'code': 500,
                        'message': "订单生成失败!"
                    })

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)